package ext.tianma.listener;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import ext.tianma.part.VirtualPartNumber;
import ext.tianma.part.Interface.MDMCheckInterface.Service.PartCheckService;
import ext.tianma.util.PhantomPolarizerUtil;
import ext.tianma.part.util.ClassifictionToSourcing;
import ext.tianma.part.util.updateIBAValues.ClassificationSynchronization;
import ext.tianma.util.PropertiesUtil;
import ext.tianma.vProductJurisdiction.VProductJurisdictionProcessor;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.sun.xml.ws.rx.rm.runtime.sequence.persistent.PersistenceException;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.drawing.BorrowUtil;
import ext.drawing.BorrowWorkflowUtil;
import ext.drawing.bean.DrawingsBorrowBean;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.part.CusIBAUtil;
import ext.tianma.bom.util.ClassificationUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.PartDescriptionUtil;
import ext.tianma.part.PartWorkflowUtil;
import ext.tianma.part.forms.CreateNewPartFormProcessor;
import ext.tianma.part.forms.DescriptionUntil;
import ext.tianma.part.forms.TMTypeUtil;
import ext.tianma.part.forms.TransitFactoryUtil;
import ext.tianma.part.resolution.Resolution;
import ext.tianma.workflow.WorkItemHelper;
import ext.tianma.workflow.sendToRDPForWorkItem;
import wt.audit.AuditRecord;
import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.content.ContentServiceEvent;
import wt.doc.WTDocument;
import wt.doc.WTDocumentDependencyLink;
import wt.doc.WTDocumentMaster;
import wt.events.KeyedEvent;
import wt.events.KeyedEventListener;
import wt.fc.ObjectNoLongerExistsException;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceManagerEvent;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTArrayList;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.iba.value.litevalue.LiteIBAReferenceable;
import wt.identity.IdentityFactory;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.inf.team.ContainerTeamServiceEvent;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.mail.EMailMessage;
import wt.org.OrganizationServicesHelper;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartMaster;
import wt.part.WTPartStandardConfigSpec;
import wt.pom.Transaction;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.services.ManagerException;
import wt.services.ServiceEventListenerAdapter;
import wt.services.StandardManager;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.session.SessionUserAuditEvent;
import wt.team.TeamReference;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.VersionControlException;
import wt.vc.VersionControlHelper;
import wt.vc.VersionControlServiceEvent;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewException;
import wt.vc.views.ViewHelper;
import wt.vc.wip.WorkInProgressHelper;
import wt.vc.wip.WorkInProgressServiceEvent;
import wt.workflow.engine.WfEngineServiceEvent;
import wt.workflow.engine.WfEventAuditType;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WfAssignmentState;
import wt.workflow.work.WorkItem;
import wt.workflow.work.WorkItemLink;

public class CusPartListenerService extends StandardManager implements PDMListenerService, Serializable {
	/** Log4j Logger. */
	private static final Logger LOGGER = LogR.getLogger(CusPartListenerService.class.getName());

	private static final String PART_NUMBER_EFFECTIVE_SITE = "partNumberEffectiveSite";

	// 工艺文件
	private static final String CONTROL_DOCUMENT = ".ControlDocument";

	// 配置文件路径
	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "part" + File.separator + "config" + File.separator + "documentType.properties";

	private static PropertiesUtil ut = new PropertiesUtil(configFilePath);

	private static String originDrawingDoc = ut.getValueByKey("origin.drawing");// 工艺类原档图纸
	private static String specialDocuments = ut.getValueByKey("special.document");// ##专显专用工艺文件
	private static String processDocuments = ut.getValueByKey("process.document");// 工艺文件

	private static final long serialVersionUID = -1979670257204652265L;

	private static final String CLASSNAME = CusPartListenerService.class.getName();

	private static final String D_VIEW = "Design";

	private static WTDocument oldDoc = null;

	private static KeyedEventListener listener = null;

	// 检出事件
	private static final String POST_CHECKIN = WorkInProgressServiceEvent.POST_CHECKIN;

	WTPart testpart = null;

	private static View[] allViews = null;

	public static CusPartListenerService newCusPartListenerService() throws WTException {
		CusPartListenerService instance = new CusPartListenerService();

		instance.initialize();

		return instance;
	}

	private static String codebase = "";
	static {
		try {
			WTProperties wp = WTProperties.getLocalProperties();
			codebase = wp.getProperty("wt.server.codebase");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public String getConceptualClassname() {
		return CLASSNAME;
	}

	@Override
	protected void performStartupProcess() throws ManagerException {
		listener = new WCListenerEventListener(this.getConceptualClassname());

		getManagerService().addEventListener(listener,
				KeyedEvent.generateEventKey(WorkInProgressServiceEvent.class, WorkInProgressServiceEvent.POST_CHECKIN));

		getManagerService().addEventListener(listener, KeyedEvent.generateEventKey(WorkInProgressServiceEvent.class,
				WorkInProgressServiceEvent.POST_CHECKOUT));
		// 新建大版本（修订）
		getManagerService().addEventListener(listener,
				VersionControlServiceEvent.generateEventKey(VersionControlServiceEvent.NEW_VERSION));
		// 新建大版本前（修订前）
		getManagerService().addEventListener(listener,
				VersionControlServiceEvent.generateEventKey(VersionControlServiceEvent.PRE_NEW_VERSION));
		// 添加需要监听的事件,这里添加的是完成提交之前事件PRE_STORE
		getManagerService().addEventListener(listener,
				PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.PRE_STORE));

		// 添加需要监听的事件,这里添加的是完成提交之后事件POST_STORE
		getManagerService().addEventListener(listener,
				PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.POST_STORE));
		getManagerService().addEventListener(listener,
				PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.PRE_STORE));
		getManagerService().addEventListener(listener,
				PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.UPDATE));
		getManagerService().addEventListener(listener,
				PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.INSERT));
		getManagerService().addEventListener(listener,
				PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.PRE_REMOVE));
		getManagerService().addEventListener(listener,
				WfEngineServiceEvent.generateEventKey(WfEventAuditType.ACTIVITY_STATE_CHANGED));
		getManagerService().addEventListener(listener,
				WfEngineServiceEvent.generateEventKey(WfEventAuditType.PROCESS_STATE_CHANGED));
		getManagerService().addEventListener(listener,
				WfEngineServiceEvent.generateEventKey(WfEventAuditType.PROCESS_CONTEXT_CHANGED));
		// 上传主内容及附件监听
		getManagerService().addEventListener(listener,
				ContentServiceEvent.generateEventKey(ContentServiceEvent.POST_UPLOAD));
		// modify 编辑修改
		getManagerService().addEventListener(listener,
				PersistenceManagerEvent.generateEventKey(PersistenceManagerEvent.POST_MODIFY));

		getManagerService().addEventListener(listener,
				SessionUserAuditEvent.generateEventKey(SessionUserAuditEvent.LOGIN));
		getManagerService().addEventListener(listener,
				SessionUserAuditEvent.generateEventKey(ContainerTeamServiceEvent.CONTAINER_LOGIN));

	}

	class WCListenerEventListener extends ServiceEventListenerAdapter {
		public WCListenerEventListener(String manager_name) {
			super(manager_name);
		}

		public void notifyVetoableEvent(Object eve) throws Exception {

			// 获取当前事件监控的对象
			KeyedEvent keyedEvent = (KeyedEvent) eve;
			// 获取当前被监控的对象
			Object targetObj = keyedEvent.getEventTarget();
			// 获取监控事件
			String eventType = keyedEvent.getEventType();

			/*************************** 主要业务代码 ******************************/
			checkIBA(targetObj, eventType);
			updateTargetIBA(targetObj, eventType);
			// 校验虚拟偏光片生效地
			// checkPartSitForPart(targetObj,eventType);

			// add by xxu 2016-01-27
			if (eve instanceof VersionControlServiceEvent) {
				try {
					listenerVersionControlServiceEvent((VersionControlServiceEvent) eve);

				} catch (WTException e) {
					e.printStackTrace();
				} catch (WTPropertyVetoException e) {
					e.printStackTrace();
				}
			}

			if (eve instanceof PersistenceManagerEvent) {
				try {
					checkProperty(targetObj, eventType);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			// add by lilin 2018年11月17日11:51:28 增加文档的修订、检入检出事件发送邮件
			if (eve instanceof VersionControlServiceEvent || eve instanceof WorkInProgressServiceEvent) {

				sendEmailToBorrowDrawing(targetObj, eventType);
			}

			// add by gjw 2019年3月8日 创建受控PDF图纸时创建原档图纸文档，并创建说明关系
			ListenerService.createInitialDrawingDocAndLink(targetObj, eventType);
			// 编辑或 修订 受控PDF图纸时 更新附件内容至参考文档（原档图纸的主内容）
			ListenerService.modifyInitialDrawingDocAndLink(targetObj, eventType);
			// end
	//		System.out.println("SessionUserAuditEvent.generateEventKey(SessionUserAuditEvent.LOGIN)===>>"
	//				+ SessionUserAuditEvent.generateEventKey(SessionUserAuditEvent.LOGIN));
	//		System.out.println("StandardCustListenerService----->keyedEvent：" + keyedEvent.toString());

			if ("CONTAINER_LOGIN".equals(ContainerTeamServiceEvent.CONTAINER_LOGIN)) {
	//			System.out.println("===================获取当前登陆 用户=============");
	//			System.out.println("eventType====>>" + eventType);
	//			System.out.println("StandardCustListenerService--keyedevent:" + eventType);
	//			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
	//			System.out.println("shijian=====>>>" + df.format(new Date()));// new Date()为获取当前系统时间
				// keyedEvent.toString() = [type = login, user = GaoXin高鑫, concurrency = 1, time
				// = 1571706106401]
	//			System.out.println("StandardCustListenerService----->targetObj：" + keyedEvent.toString());
				// 根据全名查询用户
//				VProductJurisdictionProcessor.getAuditRecord();
			}
			if (WorkInProgressServiceEvent.POST_CHECKIN.equals(eventType)) {
				try {

					if (targetObj != null && targetObj instanceof WTDocument) {
						// 创建完成操作前的文档
						WTDocument oldDoc = null;
						oldDoc = (WTDocument) targetObj;
						if (TMTypeUtil.isATypeObject(oldDoc, CONTROL_DOCUMENT)) {
							/**
							 * 过滤历史数据
							 */
							WTDocumentMaster docMaster = (WTDocumentMaster) oldDoc.getMaster();
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
							Timestamp createDateTime = docMaster.getCreateTimestamp();
							String createDate = null;
							String item = null;
							if (null != createDateTime) {
								createDate = format.format(createDateTime);
							}
							if (null != createDate) {
								// 创建时间比2018-10-10前
								if ("2018-12-01".compareTo(createDate) < 0) {
									// 获取物料编号并去掉首尾空格
									if (IBAUtil.getIBAValue(oldDoc, "Item") != null) {
										item = ((String) IBAUtil.getIBAValue(oldDoc, "Item")).trim();
									}
									// 定义搜索条件，以物料编号item方式在master中搜索
									SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER,
											SearchCondition.EQUAL, item);
									QuerySpec qs = new QuerySpec(WTPartMaster.class);
									qs.appendSearchCondition(sc);
									QueryResult qr = PersistenceHelper.manager.find(qs);
									if (qr.hasMoreElements()) {
										createDescriptionLink(targetObj, eventType, CONTROL_DOCUMENT, "Item");
									} else {
										throw new WTException("输入的物料编号不存在！");
									}
								}
							}

						}
						// 如果是工艺文档
						if (TMTypeUtil.isATypeObject(oldDoc, processDocuments)
								|| TMTypeUtil.isATypeObject(oldDoc, specialDocuments)) {
							createProcessLink(targetObj, eventType, oldDoc);
						}
					} else if (targetObj != null && targetObj instanceof WTPart) {
						WTPart part = (WTPart) targetObj;

//						// 如果是虚拟偏光片
//						if (TMTypeUtil.isPhantomPolarizer(part)) {
//							WTPart wtPart = getLatestPartByPartMaster((WTPartMaster) part.getMaster());
//							if (wtPart != null) {
//								PhantomPolarizerUtil.getPartSitForPart(wtPart);
//							}
//						}
						// 如果是半成品
						if (TMTypeUtil.isSemiFinishedGood(part)) {
							WTPart wtPart = getLatestPartByPartMaster((WTPartMaster) part.getMaster());
							if (wtPart != null) {
								VirtualPartNumber.setVirtualPartNumberThree(wtPart);
							}

						}
						if (TMTypeUtil.isFinishedGood(part)) {
							WTPart partleast = getLatestPartByPartMaster((WTPartMaster) part.getMaster());
							String str = (String) IBAUtil.getIBAValue(partleast, "finishedGoodResolutionH");
							Resolution.setAttsToIBA(part);
						}
						String partCNAndENName = "";
						String departments = "";
						WTPart partleast = getLatestPartByPartMaster((WTPartMaster) part.getMaster());
						departments = (String) IBAUtil.getIBAValue(partleast, "departments");
						Vector partNumberEffectiveSite = IBAUtil.getIBAValue2(part, PART_NUMBER_EFFECTIVE_SITE);
						if (TMTypeUtil.isRawMaterial2(part)) {
							String partNumberEffectiveSite1 = partNumberEffectiveSite.toString();
							if (partNumberEffectiveSite1 != null && partNumberEffectiveSite1.contains("F13")) {
								partCNAndENName = (String) IBAUtil.getIBAValue(part, "partCNAndENName");
								if (("tape -- 单面胶带").equals(partCNAndENName) || ("tape -- 泡棉胶带").equals(partCNAndENName)
										|| ("tape -- 粘合胶带").equals(partCNAndENName)
										|| ("tape -- 导电胶带").equals(partCNAndENName)
										|| ("tape -- 绝缘胶带").equals(partCNAndENName)
										|| ("tape -- 遮光胶带").equals(partCNAndENName)
										|| ("Protective film -- 保护膜").equals(partCNAndENName)
										|| ("tape -- 双面导电胶带").equals(partCNAndENName)) {

									if (departments == null || departments.isEmpty()) {
										throw new WTException("请选择所属部门！");
									}
								}
							}
						}

					}
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// //如果点击完成任务，则删除当前任务节点
			// if (eventType.equals(PersistenceManagerEvent.POST_STORE) && targetObj
			// instanceof WorkItemLink) {
			// System.out.println("完成任务 222 START COMPLETED===================>>>>");
			// }
			// 监听任务代办发送到RDP
			if (eventType.equals(PersistenceManagerEvent.INSERT) && targetObj instanceof WorkItemLink) {
				// 监听流程任务
				LOGGER.debug("--------------->workitemlink insert event target created!");
				WorkItemLink link = (WorkItemLink) targetObj;
				WorkItem workitem = link.getWorkItem();
				WfProcess process = null;
				String processName = "";
				String username = "";
				String msg = "";
				String activityname = "";
				String url = "";
				String processId = "";
				String contentUrl = "";
				String startUserId = "";
				String source = "PLM";
				String tenantId = "2";
				String dateTime = "";
				String workItemId = "";
				String processState = "";
				String workItemStatus = "";
				String ownerID = "";
				String pboName = "";
				String errMsg = "";

				// 获取工作流任务名称（节点名称）
				WfAssignedActivity waa = (WfAssignedActivity) workitem.getSource().getObject();
				activityname = waa.getName();
				LOGGER.debug("activityname--------------->" + activityname);

				// 获取workItem状态
				workItemStatus = workitem.getStatus().toString(); // 获取工作流
				process = waa.getParentProcess();
				processName = process.getName();
				LOGGER.debug("process========>>>>" + process.getName());
				LOGGER.debug("processState===>>>>" + process.getState());
				LOGGER.debug("workItem=======>>>>" + workitem.getStatus());

				// 获取执行者
				WTPrincipal principal = workitem.getOwnership().getOwner().getPrincipal();
				username = ((WTUser) principal).getFullName();

				LOGGER.debug("username--------------->" + username);

				// 任务详细信息url
				String object_ref = (new wt.fc.ReferenceFactory()).getReferenceString(workitem);
				url = codebase + "/app/#ptc1/tcomp/infoPage?oid=" + object_ref;
				LOGGER.debug("url=====>>>>" + url);

				// 获取流程实例ID
				long procInstId = process.getPersistInfo().getObjectIdentifier().getId();
				processId = String.valueOf(procInstId);

				// 获取流程主内容
				contentUrl = WorkItemHelper.getUrl(process);

				// 获取流程启动人工号 startUserId
				startUserId = WorkItemHelper.getStartUserId(process);

				// 获取分配时间
				dateTime = WorkItemHelper.getDueDate(workitem);

				// 获取workItem Id
				workItemId = String.valueOf(workitem.getPersistInfo().getObjectIdentifier().getId());

				// 流程状态
				processState = process.getState().toString(); // 获取任务处理人工号 assignee
				ownerID = WorkItemHelper.getAssignee(workitem);

				// 获取主对象名称
				pboName = WorkItemHelper.getPBOName(process);
				// 判断流程状态是否处于正在运行，否则调用删除流程接口
				if (process.getState().equals(WfState.OPEN_RUNNING)) {
					LOGGER.debug("=====111====="); // 查看状态是否已完成
					if (workitem.getStatus().equals(WfAssignmentState.POTENTIAL)) {
						LOGGER.debug("=====222====="); // 流程正在运行，调用传入任务到RDP接口
						errMsg = sendToRDPForWorkItem.sendWorkItemToRDP(processName, username, msg, activityname, url,
								processId, contentUrl, startUserId, source, tenantId, dateTime, workItemId,
								processState, workItemStatus, ownerID, pboName);
					} else if (workitem.getStatus().equals(WfAssignmentState.COMPLETED)) {
						LOGGER.debug("=====333=====");
						errMsg = sendToRDPForWorkItem.sendWorkItemToRDPForPost(workItemId, source, processId, false);
					}
				} else {
					LOGGER.debug("=============444=============");
					// 调用通过流程id删除接口 sendWorkItemToERP
					errMsg = sendToRDPForWorkItem.sendWorkItemToRDP(processId, "PLM");
				}

			} else if (eventType.equals(PersistenceManagerEvent.UPDATE) && targetObj instanceof WorkItem) {
				// 用户点击查看任务后，未必执行此任务，因此此时机删除待办，是否正确？
				WorkItem item = (WorkItem) targetObj;
				if (item.getStatus().equals(WfAssignmentState.COMPLETED)) {
					boolean flagAccess = SessionServerHelper.manager.setAccessEnforced(false); // 监听流程任务
					WorkItem workitem = (WorkItem) targetObj;
					WfProcess process = null;
					String processId = "";
					String source = "PLM";
					String workItemId = "";
					String errMsg = "";

					String activityname = ""; // 获取工作流任务名称（节点名称）
					WfAssignedActivity waa = (WfAssignedActivity) workitem.getSource().getObject();
					activityname = waa.getName();

					// 获取工作流
					process = waa.getParentProcess();

					// 获取流程实例ID
					long procInstId = process.getPersistInfo().getObjectIdentifier().getId();
					processId = String.valueOf(procInstId);

					// 获取workItem Id
					workItemId = String.valueOf(workitem.getPersistInfo().getObjectIdentifier().getId());

					// 判断流程状态是否处于正在运行，否则调用删除流程接口
					if (process.getState().equals(WfState.OPEN_RUNNING)) {
						errMsg = sendToRDPForWorkItem.sendWorkItemToRDPForPost(workItemId, source, processId, false);
					} else {
						// 调用通过流程id删除接口 sendWorkItemToERP
						errMsg = sendToRDPForWorkItem.sendWorkItemToRDP(processId, "PLM");
					}
					SessionServerHelper.manager.setAccessEnforced(flagAccess);

				} // 重新指派后被指派的人需要生成代办通知 以及删除指派人代办
				else if (item.getStatus().equals(WfAssignmentState.POTENTIAL) && item.isReassigned()) {
					LOGGER.debug("--------------->workitemlink insert event target created!");
					WfProcess process = null;
					String processName = "";
					String username = "";
					String msg = "";
					String activityname = "";
					String url = "";
					String processId = "";
					String contentUrl = "";
					String startUserId = "";
					String source = "PLM";
					String tenantId = "2";
					String dateTime = "";
					String workItemId = "";
					String processState = "";
					String workItemStatus = "";
					String ownerID = "";
					String pboName = "";
					String errMsg = "";

					// 获取工作流任务名称（节点名称）
					WfAssignedActivity waa = (WfAssignedActivity) item.getSource().getObject();
					activityname = waa.getName();

					// 获取workItem状态
					workItemStatus = item.getStatus().toString(); // 获取工作流
					process = waa.getParentProcess();
					processName = process.getName();

					// 获取执行者
					WTPrincipal principal = item.getOwnership().getOwner().getPrincipal();
					username = ((WTUser) principal).getFullName();
					WTUser assigneeUser = (WTUser) item.getOwnership().getOwner().getObject();
					String assignee = WorkItemHelper.getAlternateName(assigneeUser, "alternateUserName1");

					// 任务详细信息url
					String object_ref = (new wt.fc.ReferenceFactory()).getReferenceString(item);
					url = codebase + "/app/#ptc1/tcomp/infoPage?oid=" + object_ref;

					// 获取流程实例ID
					long procInstId = process.getPersistInfo().getObjectIdentifier().getId();
					processId = String.valueOf(procInstId);

					// 获取流程主内容
					contentUrl = WorkItemHelper.getUrl(process);

					// 获取流程启动人工号 startUserId
					startUserId = WorkItemHelper.getStartUserId(process);

					// 获取分配时间
					dateTime = WorkItemHelper.getDueDate(item);

					// 获取workItem Id

					workItemId = String.valueOf(item.getPersistInfo().getObjectIdentifier().getId());

					// 流程状态
					processState = process.getState().toString(); // 获取任务处理人工号 assignee
					ownerID = WorkItemHelper.getAssignee(item);
					LOGGER.debug("ownerID====" + ownerID);

					// 获取主对象名称
					pboName = WorkItemHelper.getPBOName(process);

					errMsg = sendToRDPForWorkItem.sendWorkItemToRDPForPost(workItemId, source, processId, false);
					// 流程正在运行，调用传入任务到RDP接口
					errMsg = sendToRDPForWorkItem.sendWorkItemToRDP(processName, username, msg, activityname, url,
							processId, contentUrl, startUserId, source, tenantId, dateTime, workItemId, processState,
							workItemStatus, ownerID, pboName);
				}

			}
			if (eventType.equals(PersistenceManagerEvent.PRE_REMOVE) && targetObj instanceof WorkItem) {
				WorkItem items = (WorkItem) targetObj;
				LOGGER.debug("====remove===");

			}
			LOGGER.debug("---------eventType----------" + eventType);
			LOGGER.debug("---------WfEventAuditType.PROCESS_STATE_CHANGED----------"
					+ WfEventAuditType.PROCESS_STATE_CHANGED);
			if (eventType.equals("PROCESS_STATE_CHANGED") && targetObj instanceof WfProcess) {
				LOGGER.debug("终止流程--------------------------->>>>>>");
				WfProcess wfProcess = (WfProcess) targetObj;
				LOGGER.debug("wfProcess.getState();------------>>>>>" + wfProcess.getState());
				if (wfProcess.getState().equals(WfState.CLOSED_TERMINATED)) {
					LOGGER.debug("终止状态--------------------------->>>>>>");
					long procInstId = wfProcess.getPersistInfo().getObjectIdentifier().getId();
					String processId = String.valueOf(procInstId);
					String errMsg = sendToRDPForWorkItem.sendWorkItemToRDP(processId, "PLM"); //
					LOGGER.debug("errMsg=====>>" + errMsg);
				}
				LOGGER.debug("====remove2===");
			}
		}
		
		/**
		 * MDM检验分类属性是否正确
		 * @param targetObj
		 * @param eventType
		 * @throws WTException
		 */
		private void checkIBA(Object targetObj, String eventType) throws WTException {
			//部件编辑完成之后校验分类属性是否规范 -- by sunlaichao 
			if (eventType != null && eventType.equals(POST_CHECKIN)) {
				if (targetObj != null && targetObj instanceof WTPart) {
					WTPart part2 = null;
					WTPart oldPart = (WTPart) targetObj;
				
					if(TMTypeUtil.isFinishedGood(oldPart)||TMTypeUtil.isSemiFinishedGood(oldPart)||TMTypeUtil.isRawMaterial(oldPart)) {
						try {
							System.out.println("SLC ==检入MDM校验(先行进入监听开始)==>"+oldPart.getNumber()+" | "+oldPart.getView());
	                        part2 = CoreUtil.getWTPartByMasterAndView((WTPartMaster) oldPart.getMaster(), oldPart.getViewName());
	                        String classification = ClassificationUtil.getClassification(part2);
	                        if (StringUtil.isNullOrEmpty(classification)) {
	                        	return;
	                        }else {
	                        	PartCheckService.sendCheckService(part2);
	                        }
							System.out.println("SLC ==检入MDM校验(先行进入监听结束)==>"+oldPart.getNumber()+" | "+oldPart.getView());
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}else {
						return;
					}
				}
			}
		}

		/**
		 * 创建工艺文件link
		 * 
		 * @param targetObj
		 * @param eventType
		 * @param oldDoc
		 * @throws WTException
		 * @throws RemoteException
		 */
		private void createProcessLink(Object targetObj, String eventType, WTDocument oldDoc)
				throws WTException, RemoteException {

			documentLink(targetObj, eventType, oldDoc, processDocuments);
			documentLink(targetObj, eventType, oldDoc, specialDocuments);
		}

		private void documentLink(Object targetObj, String eventType, WTDocument oldDoc, String documentType)
				throws WTException, RemoteException {
			if (TMTypeUtil.isATypeObject(oldDoc, documentType)) {
				String item = null;
				// 获取物料编号并去掉首尾空格
				if (IBAUtil.getIBAValue(oldDoc, "productNumber") != null) {
					item = ((String) IBAUtil.getIBAValue(oldDoc, "productNumber")).trim();
				}
				// 定义搜索条件，以物料编号item方式在master中搜索
				if (item == null) {
					return;
				}
				SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
						item);
				QuerySpec qs = new QuerySpec(WTPartMaster.class);
				qs.appendSearchCondition(sc);
				QueryResult qr = PersistenceHelper.manager.find(qs);
				if (qr.hasMoreElements()) {
					createDescriptionLink(targetObj, eventType, documentType, "productNumber");
				} else {
					throw new WTException("输入的物料编号不存在！");
				}
			}
		}

		/**
		 * 校验虚拟偏光片料号生效地
		 * 
		 * @param targetObj
		 * @param eventType
		 * @throws Exception
		 */
		public void checkPartSitForPart(Object targetObj, String eventType) throws Exception {
			if (eventType != null && PersistenceManagerEvent.POST_STORE.equals(eventType)) {

				if (targetObj != null && targetObj instanceof WTPart) {
					WTPart part = (WTPart) targetObj;
					if (TMTypeUtil.isPhantomPolarizer(part)) {
						PhantomPolarizerUtil.getPartSitForPart(part);
					}
				}

			}
		}

		/**
		 * 图纸完成后自动创建DescriptionLink
		 * 
		 * @author he_zhang2
		 * @param targetObj
		 * @param eventType
		 * @return
		 * @throws WTException
		 * @throws RemoteException
		 */
		public void createDescriptionLink(Object targetObj, String eventType, String typeName, String attributeName)
				throws WTException, RemoteException {
			if (eventType != null && PersistenceManagerEvent.POST_STORE.equals(eventType)) {
				if (targetObj != null && targetObj instanceof WTDocument) {
					WTDocument doc = null;
					doc = (WTDocument) targetObj;
					if (TMTypeUtil.isATypeObject(doc, typeName)) {
						String item = ((String) IBAUtil.getIBAValue(doc, attributeName)).trim();
						// 获取物料的Design视图对象
						WTPart dpart = null;
						dpart = (WTPart) CoreUtil.getWTPartByNumberAndView(item, "Design");
						// 获取物料的其他所有视图对象
						WTArrayList partList = new WTArrayList();
						partList = PartWorkflowUtil.getAllPartViews(dpart);
						partList.add(dpart);
						// 创建DescriptionLink
						for (int i = 0; i < partList.size(); i++) {
							WTPart wtpart = null;
							wtpart = (WTPart) partList.getPersistable(i);
							WTPartDescribeLink link = WTPartDescribeLink.newWTPartDescribeLink(wtpart, doc);
							PersistenceServerHelper.manager.insert(link);
						}
					}
				}
			}
		}

		/**
		 * 
		 * 创建受控图纸结束时物料编号合理性检查
		 * 
		 * @author he_zhang2
		 * @param targetObj
		 * @param eventType
		 * @return exist
		 * @throws WTException
		 * @throws RemoteException
		 */
		public boolean checkProperty(Object targetObj, String eventType) throws WTException, RemoteException {
			boolean property = false;

			if (eventType != null && PersistenceManagerEvent.POST_STORE.equals(eventType)) {
				if (targetObj != null && targetObj instanceof WTDocument) {
					// 创建完成操作前的文档
					WTDocument oldDoc = null;
					oldDoc = (WTDocument) targetObj;
					if (TMTypeUtil.isATypeObject(oldDoc, CONTROL_DOCUMENT)) {
						/**
						 * 过滤历史数据
						 */
						WTDocumentMaster docMaster = (WTDocumentMaster) oldDoc.getMaster();
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						Timestamp createDateTime = docMaster.getCreateTimestamp();
						String createDate = null;
						String item = null;
						if (null != createDateTime) {
							createDate = format.format(createDateTime);
						}
						if (null != createDate) {
							// 创建时间比2018-10-10前
							if ("2018-12-01".compareTo(createDate) < 0) {
								// 获取物料编号并去掉首尾空格
								if (IBAUtil.getIBAValue(oldDoc, "Item") != null) {
									item = ((String) IBAUtil.getIBAValue(oldDoc, "Item")).trim();
								}
								// 定义搜索条件，以物料编号item方式在master中搜索
								SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER,
										SearchCondition.EQUAL, item);
								QuerySpec qs = new QuerySpec(WTPartMaster.class);
								qs.appendSearchCondition(sc);
								QueryResult qr = PersistenceHelper.manager.find(qs);
								if (qr.hasMoreElements()) {
									createDescriptionLink(targetObj, eventType, CONTROL_DOCUMENT, "Item");
									property = true;
								} else {
									throw new WTException("输入的物料编号不存在！");
								}
							}
						}
					}
					// 创建时工艺文件的连接
					if (TMTypeUtil.isATypeObject(oldDoc, processDocuments)
							|| TMTypeUtil.isATypeObject(oldDoc, specialDocuments)) {
						createProcessLink(targetObj, eventType, oldDoc);
					}
				}
			}

			return property;
		}

		/**
		 * 受控文档修订时关联的原档图纸同时升版本再关联
		 * 
		 * @param event
		 * @throws WTException
		 * @throws WTPropertyVetoException
		 */
		private void listenerVersionControlServiceEvent(VersionControlServiceEvent event)
				throws WTException, WTPropertyVetoException {
			Object object = event.getEventTarget();
			// WTDocument oldDoc = null;
			if (VersionControlServiceEvent.PRE_NEW_VERSION.equals(event.getEventType())) {
				if (object instanceof WTDocument) {
					oldDoc = (WTDocument) object;
					LOGGER.debug("oldDoc === " + IdentityFactory.getDisplayIdentifier(oldDoc));
				}
			}

			if (oldDoc != null) {
				if (VersionControlServiceEvent.NEW_VERSION.equals(event.getEventType())) {

					if (object instanceof WTDocument) {
						WTDocument doc = (WTDocument) object;
						LOGGER.debug("doc ======= " + IdentityFactory.getDisplayIdentifier(doc));
						String typeInternal = getSoftTypeInternal(doc);
						// 如果是受控pdf文档，则是受控pdf文档和受控pdf原档图纸关联
						if (typeInternal.equals(CONTROL_DOCUMENT)) {
							editDoc(doc, "InitialDrawingDoc");
						}
						// 如果是工艺文档，则是和工艺类原档图纸关联
						if (typeInternal.equals(processDocuments) || typeInternal.equals(specialDocuments)) {
							editDoc(doc, "ProcessOriginDrawingDoc");
						}

					}
				}
			}

		}

		/**
		 * 受控文档和原档图纸关联
		 * 
		 * @param doc
		 * @param drawingDoc
		 * @throws WTException
		 */
		private void editDoc(WTDocument doc, String drawingDoc) throws WTException {
			String majorVersion = CommonPDMUtil.getMajorVersion(doc);
			String minorVersion = CommonPDMUtil.getMinorVersion(doc);
			QueryResult qr = PersistenceHelper.manager.navigate(doc, "describedBy", WTDocumentDependencyLink.class,
					false);
			if (qr != null) {
				while (qr.hasMoreElements()) {
					WTDocumentDependencyLink link = (WTDocumentDependencyLink) qr.nextElement();
					WTDocument relateDoc = link.getDependsOn();
					LOGGER.debug("relateDoc === " + IdentityFactory.getDisplayIdentifier(relateDoc));
					if (getSoftTypeInternal(relateDoc).equals(drawingDoc)) {
						if ((!majorVersion.equals("0")) && minorVersion.equals("0")) {
							if (oldDoc.getNumber().equals(doc.getNumber())) {
								WTDocument newVersionDoc = getNewVersionDoc(relateDoc);
								boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
								try {
									newVersionDoc = (WTDocument) LifeCycleHelper.service
											.setLifeCycleState(newVersionDoc, State.INWORK);
								} finally {
									SessionServerHelper.manager.setAccessEnforced(flag);
								}
								PersistenceServerHelper.manager.remove(link);
								WTDocumentDependencyLink dependencyLink = WTDocumentDependencyLink
										.newWTDocumentDependencyLink(doc, newVersionDoc);

								PersistenceServerHelper.manager.insert(dependencyLink);

								// updateContent(doc ,
								// newVersionDoc);
								break;
							}

						}

					}

				}

			}
		}

		private void updateContent(WTDocument doc, WTDocument newVersionDoc)
				throws WTException, WTPropertyVetoException {

			QueryResult result = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
			ApplicationData data = null;
			while (result.hasMoreElements()) {
				data = (ApplicationData) result.nextElement();

			}
			if (data != null) {
				ContentServerHelper.service.deleteContent(doc, data);
			}

			// ApplicationData appData =
			// ApplicationData.newApplicationData(doc);
			// appData.setRole(ContentRoleType.PRIMARY);
			//
			// appData = ContentServerHelper.service.updateContent(doc,
			// appData,);
			// PersistenceServerHelper.manager.update(appData);

		}

		/**
		 * 对文档对象升大版本
		 * 
		 * @param doc
		 * @return
		 */
		public WTDocument getNewVersionDoc(WTDocument doc) {

			WTDocument wtdocument = doc;
			LOGGER.debug("doc ======" + IdentityFactory.getDisplayIdentifier(doc));
			Transaction tx = null;
			try {
				tx = new Transaction();
				tx.start();
				if (wtdocument == null) {
					return null;
				}
				WTContainer container = wtdocument.getContainer();
				WTContainerRef containerRef = WTContainerRef.newWTContainerRef(container); // container.getContainerReference();//
				TeamReference teamReference = wtdocument.getTeamId();
				Folder oldFoler = FolderHelper.getFolder(wtdocument);
				if (oldFoler == null) {
					String strLocation = wtdocument.getLocation();
					oldFoler = FolderHelper.service.getFolder(strLocation, containerRef);
				}

				wtdocument = (WTDocument) wt.vc.VersionControlHelper.service.newVersion((wt.vc.Versioned) wtdocument);

				if (teamReference != null) {
					wtdocument.setTeamId(teamReference);
				}
				wtdocument.setContainer(container);

				FolderHelper.assignLocation((FolderEntry) wtdocument, oldFoler);

				wtdocument = (WTDocument) PersistenceHelper.manager.save(wtdocument);
				wtdocument = (WTDocument) PersistenceHelper.manager.refresh(wtdocument);

				tx.commit();
				tx = null;
			} catch (VersionControlException e) {

				e.printStackTrace();
			} catch (WTPropertyVetoException e) {

				e.printStackTrace();
			} catch (ObjectNoLongerExistsException e) {

				e.printStackTrace();
			} catch (WTException e) {

				e.printStackTrace();
			} finally {
				// 出现异常，事物回滚
				if (tx != null) {
					tx.rollback();
				}
			}

			LOGGER.debug("wtdocument ======" + IdentityFactory.getDisplayIdentifier(wtdocument));
			return wtdocument;
		}

		/**
		 * 获取WTObject对象的软类型的内部值
		 * 
		 * @param obj
		 * @return
		 */
		public String getSoftTypeInternal(WTObject obj) {
			String internalName = "";

			if (obj != null) {
				try {
					// 获取完整的内部值
					internalName = ClientTypedUtility.getTypeIdentifier(obj).getTypename();

					if (internalName != null) {
						int startIndex = internalName.lastIndexOf(".") + 1;

						// 截取最后一个"."的后面部分
						internalName = internalName.substring(startIndex);
					}
				} catch (WTException e) {
					e.printStackTrace();
				}
			}

			return internalName;
		}

		/**
		 * 修改“Desgin”视图后，更新其他视图对象
		 * 
		 * @param targetObj
		 * @param eventType
		 */
		private void updateTargetIBA(Object targetObj, String eventType) throws WTException {
			
			// 修改“Desgin”视图后，更新其他视图对象
			if (eventType != null && eventType.equals(POST_CHECKIN)) {
				if (targetObj != null && targetObj instanceof WTPart) {
					WTPart part = null;
					WTPart oldPart = (WTPart) targetObj;
					// 二级物料只有“Desgin”视图没有其他视图，所以不存在多视图同步IBA属性
					if (TMTypeUtil.isTwoLevelMaterial(oldPart)) {
						return;
					}
					if (isPartViewDesgin(oldPart)) {
						try {
							part = CoreUtil.getWTPartByMasterAndView((WTPartMaster) oldPart.getMaster(), D_VIEW);

							// 同步非Design视图下的其他视图的虚拟料号
							if (TMTypeUtil.isSemiFinishedGood(part)) {
								VirtualPartNumber.setVirtualPartNumberTwo(part);
							}

							if (TMTypeUtil.isRawMaterial(part)) {
								if (!TMTypeUtil.isPhantomPolarizer(part)) {
									if (!TMTypeUtil.isPolarizer(part)) {
										CreateNewPartFormProcessor.setCNAndENName(part);
									} else if (TMTypeUtil.isTopPolarizer(part) || (TMTypeUtil.isBotPolarizer(part))) {
										/**
										 * @author xuge_ning
										 * @time 2017-1-6
										 * @reason 偏光片尺寸和mark值的修改
										 * 
										 *         if (! CreateNewPartFormProcessor .checkPartSize(part)) { throw new
										 *         WTException( "尺寸信息请输入保留两位小数的数字！"); }
										 */
										// 如果为上片
										if (TMTypeUtil.isTopPolarizer(part)) {
											CreateNewPartFormProcessor.checkTopPolarizerAtt(part);
											// 如果为下片
										} else if (TMTypeUtil.isBotPolarizer(part)) {
											CreateNewPartFormProcessor.checkBotPolarizerAtt(part);
										}

									}
								}
								// 修改中英文名称之后，同步修改物料的PartName和更新零部件默认单位，addby
								// xuge_ning
								CreateNewPartFormProcessor.updateRawMaterialInfo(part);
								ClassifictionToSourcing.getClassifiByPart(part);
							}

							//修改原材料物料描述 -- by sunlaichao 未上线
							//PartDescriptionUtil.setPartDescription(part);
							DescriptionUntil.setPartDescription(part);

							if (!TMTypeUtil.isFinishedGood(part)) {
								PartDescriptionUtil.setPartDescriptionDetail(part);
							}

							/**
							 * @author xuge_ning 设置分类属性传sourcing值的修改
							 */
							// setTotalToSourcing(part);
							allViews = ViewHelper.service.getAllViews();
						} catch (ViewException e) {
							e.printStackTrace();
						} catch (NumberFormatException e) {
							e.printStackTrace();
						}
						boolean accessEnforced = SessionServerHelper.manager.setAccessEnforced(false);
						if (allViews != null && allViews.length > 1) {

							try {
								Hashtable values = IBAUtil.getIBAValues(part);

								for (int i = 0; i < allViews.length; i++) {
									if (allViews[i] != null && !D_VIEW.equals(allViews[i].getName())) {
										updateTargetIBA(part, allViews[i], values);
									}
								}
							} catch (WTException e) {
								e.printStackTrace();
							} catch (RemoteException e) {
								e.printStackTrace();
							} finally {
								SessionServerHelper.manager.setAccessEnforced(accessEnforced);
							}
						}
					}
				}
			}
		}

		/**
		 * 修改“Desgin”视图后，更新其他视图对象
		 * 
		 * @param part
		 * @param partNumber
		 * @param nextView
		 * @throws WTException
		 * @throws RemoteException
		 */
		private void updateTargetIBA(WTPart part, View aView, Hashtable values) throws WTException, RemoteException {
			WTPart nextPart = getWTPartByMasterAndView((WTPartMaster) part.getMaster(), aView);

			if (nextPart != null && !D_VIEW.equals(nextPart.getViewName())) {
				if (!WorkflowUtil.isObjectCheckedOut(nextPart)) {
					nextPart = (WTPart) CoreUtil.checkoutObject(nextPart);
				}
				/**
				 * @author xuge_ning 成品模组产地枚举值的处理
				 */
				if (TMTypeUtil.isFinishedGood(part)) {

					Vector modelOrigin = IBAUtil.getIBAValue2(part, "moduleOrigin");
					LOGGER.debug(CLASSNAME + "模组产地：modelOrigin:" + modelOrigin.toString());
					String model = "";
					if (modelOrigin != null) {
						for (int i = 0; i < modelOrigin.size(); i++) {
							Object obj = modelOrigin.get(i);
							if (obj != null && obj instanceof String) {
								if (model.equals("")) {
									model = (String) obj;
								} else {
									model = model + "," + (String) obj;
								}
							}
						}
						LOGGER.debug(CLASSNAME + "模组产地：model：" + model);
						CusIBAUtil.forceSetEnumIBAValue(nextPart, "moduleOrigin", model);
					}
				}
				TransitFactoryUtil.copyIBAValues(values, nextPart);
				CoreUtil.checkinObject(nextPart, "监听程序同步IBA属性");
			}
		}

		/**
		 * 判断对象的视图是否为“Desgin”
		 * 
		 * @param part
		 * @return
		 */
		private boolean isPartViewDesgin(WTPart part) {
			boolean isPartViewDesgin = false;

			if (part == null) {
				return isPartViewDesgin;
			}

			if (D_VIEW.equals(part.getViewName())) {
				isPartViewDesgin = true;
			}

			return isPartViewDesgin;
		}

	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	private static WTPart getWTPartByMasterAndView(WTPartMaster master, View view) throws WTException {
		WTPart part = null;

		// 根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(view, null);
		try {
			standardConfig.setView(view);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		// 根据master和视图获取对应最新的视图版本零部件
		QueryResult qr1 = ConfigHelper.service.filteredIterationsOf(master, standardConfig);
		if (qr1.hasMoreElements()) {
			part = (WTPart) qr1.nextElement();
		}
		return part;
	}

	public static void setTotalToSourcing(WTPart part) {
		/**
		 * @author xuge_ning 分类属性传sourcing
		 *         SurfaceStructTypeD-SizeT-Color-partApplicationReason
		 *         -isSecondSupplier-partSupplier SurfaceStructTypeD-SizeT-Color-
		 *         partApplicationReason-isSecondSupplier-partSupplier begin
		 */

		// getClassNodesByPart(part);
		try {
			LOGGER.debug(CLASSNAME + " <<< Part "
					+ ((LiteIBAReferenceable) (IBAUtil.getIBAValue(part, "Part"))).getIBAReferenceableDisplayString());
			String classificationNode = ((LiteIBAReferenceable) IBAUtil.getIBAValue(part, "Part"))
					.getIBAReferenceableDisplayString();
			String totalToSourcing1 = (String) IBAUtil.getIBAValue(part, "TotalToSourcing");
			LOGGER.debug(CLASSNAME + " <<< Part " + classificationNode);
			LOGGER.debug(CLASSNAME + " TotalToSourcing " + IBAUtil.getIBAValue(part, "TotalToSourcing"));
			LOGGER.debug(CLASSNAME + " <<< totalToSourcing " + totalToSourcing1);
			System.out
					.println(CLASSNAME + " <<< SurfaceStructTypeD " + IBAUtil.getIBAValue(part, "SurfaceStructTypeD"));
			LOGGER.debug(CLASSNAME + " <<< SizeT " + IBAUtil.getIBAValue(part, "SizeT"));
			LOGGER.debug(CLASSNAME + " <<< Color " + IBAUtil.getIBAValue(part, "Color"));
			LOGGER.debug(
					CLASSNAME + " <<< partApplicationReason " + IBAUtil.getIBAValue(part, "partApplicationReason"));
			LOGGER.debug(CLASSNAME + " <<< isSecondSupplier " + IBAUtil.getIBAValue(part, "isSecondSupplier"));
			LOGGER.debug(CLASSNAME + " <<< partSupplier " + IBAUtil.getIBAValue(part, "partSupplier"));
			LOGGER.debug(CLASSNAME + " <<< getCreatorFullName " + part.getCreatorFullName());
			LOGGER.debug(
					CLASSNAME + " <<< partApplicationReason " + IBAUtil.getIBAValue(part, "partApplicationReason"));
			/*
			 * IBAUtil.forceSetIBAValue(part, "classToSourcing", "classToSourcing");
			 * LOGGER.debug(CLASSNAME + " classToSourcing " + IBAUtil.getIBAValue(part,
			 * "classToSourcing")); IBAUtil.forceSetIBAValue(part,
			 * "classificationToSourcing", "classificationToSourcing");
			 * LOGGER.debug(CLASSNAME + " classificationToSourcing " +
			 * IBAUtil.getIBAValue(part, "classificationToSourcing"));
			 */
			if (classificationNode != null && !"".equals(classificationNode)) {
				String totalToSourcing = (String) IBAUtil.getIBAValue(part, "TotalToSourcing");
				if (totalToSourcing != null && !"".equals(totalToSourcing)) {

					String[] paramList = totalToSourcing.split("-");
					StringBuffer valueList = new StringBuffer("");
					int length = paramList.length;
					if (length > 0) {
						for (int i = 0; i < length; i++) {
							String param = paramList[i].trim();
							if (param != null && !"".equals(param)) {
								String paramValue = (String) IBAUtil.getIBAValue(part, param);
								if (paramValue != null && !"".equals(paramValue)) {
									if (valueList.length() <= 0) {
										valueList.append(paramValue);
									} else {
										valueList.append(paramValue + "-");
									}
								}
							}
						}
						String creator = part.getCreatorFullName();
						valueList.append(creator);
					}
					LOGGER.debug(CLASSNAME + " <<< valueList " + valueList);
					IBAUtil.forceSetIBAValue(part, "classToSourcing", valueList.toString());
					LOGGER.debug(CLASSNAME + " classToSourcing " + IBAUtil.getIBAValue(part, "classToSourcing"));
				}
			}

			/**
			 * end
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 文档修订之后，给借阅的人发送变更邮件通知
	 * 
	 * @author lilin 2018年11月17日11:50:59
	 * 
	 * @param targetObj
	 *            监听对象
	 * @param eventType
	 *            监听事件类型
	 * @throws WTException
	 */
	public static void sendEmailToBorrowDrawing(Object targetObj, String eventType) throws WTException {
		if (VersionControlServiceEvent.NEW_VERSION.equals(eventType)// 修订
				|| WorkInProgressServiceEvent.POST_CHECKIN.equals(eventType)) {// 检入检出

			if (targetObj != null && targetObj instanceof WTDocument) {
				WTDocument doc = (WTDocument) targetObj;// 获取document对象

				List<DrawingsBorrowBean> dbs = BorrowUtil.getDrawingBorrowByNumber(doc.getNumber());// 通过number查询中间表，获取借阅信息列表
				String emailAddr = "";
				if (dbs.size() > 0) {
					for (int i = 0; i < dbs.size(); i++) {
						DrawingsBorrowBean db = dbs.get(i);
						String userName = db.getBorrowUser();
						WTUser user = BorrowWorkflowUtil.getUserFromName(userName);
						emailAddr += user.getEMail() + ";";// 拼接电子邮件，多个人用；隔开
					}

					// 邮件内容
					StringBuffer body = new StringBuffer();
					body.append("您借阅的:[" + doc.getNumber() + "]图文档已经被修订，如需借阅，请重新提交申请流程。<br>");
					// String[] emailSendTo = emailAddr.split(";");
					String[] emailSendTo = "".equals(emailAddr) || emailAddr == null ? null : emailAddr.split(";");
					EMailMessage email = EMailMessage.newEMailMessage();
					email.addEmailAddress(emailSendTo);
					// 邮件主题
					StringBuffer title = new StringBuffer();
					title.append("您借阅的[" + doc.getNumber() + "]图文档已经被修订！");
					email.setSubject(title.toString());
					email.setMultipartSubtype("text/html;charset=\"UTF8\"");
					email.addPart(body.toString(), "text/html;charset=\"UTF8\"");
					email.send(false);
				}

			}
		}
	}

	/**
	 * 判断该document是否已经出库
	 * 
	 * @param document
	 *            document对象
	 * @return true:出库<br>
	 *         false:未出库
	 */
	public static boolean isCheckOut(WTDocument document) {
		boolean isCheckOut = false;
		if (document != null) {
			try {
				isCheckOut = WorkInProgressHelper.isCheckedOut(document);/* 获取document的出库状态 */
			} catch (WTException e) {
				e.printStackTrace();
			}
		} // end if

		return isCheckOut;
	}

	/**
	 * + 根据WTDocumentMaster获得最新版WTDocument
	 * 
	 * @param docMaster
	 * @return
	 * @throws WTException
	 * @throws PersistenceException
	 * @throws Exception
	 */
	private WTDocument getLatestDocument(WTDocumentMaster docMaster) throws PersistenceException, WTException {
		WTDocument document = null;
		if (docMaster != null) {
			QueryResult qr = VersionControlHelper.service.allVersionsOf(docMaster);
			if (qr != null && qr.hasMoreElements()) {
				document = (WTDocument) qr.nextElement();
			}
		}
		return document;
	}

	public static WTPart getLatestPartByPartMaster(WTPartMaster paramWTPartMaster) throws WTException {
		return getWtPart(paramWTPartMaster);
	}

	public static WTPart getWtPart(WTPartMaster paramWTPartMaster) throws WTException {
		Iterated localIterated = null;
		boolean bool = false;
		LatestConfigSpec localLatestConfigSpec = new LatestConfigSpec();

		QueryResult localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster,
				localLatestConfigSpec);
		if ((localQueryResult != null) && (localQueryResult.size() <= 0)) {
			ConfigSpec localConfigSpec = ConfigHelper.service.getDefaultConfigSpecFor(WTPartMaster.class);
			localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster, localConfigSpec);
		}

		while ((localQueryResult.hasMoreElements()) && (!bool)) {
			localIterated = (Iterated) localQueryResult.nextElement();
			bool = localIterated.isLatestIteration();
		}
		return (WTPart) localIterated;

	}

	public static WTUser getUserByFullName(String fullName) throws WTException {
		Enumeration users = OrganizationServicesHelper.manager.findLikeUser("fullName", fullName);
		while (users.hasMoreElements()) {
			Object obj = users.nextElement();
			if (obj instanceof WTUser) {
				WTUser wtuser = (WTUser) obj;
				return wtuser;
			}
		}
		return null;
	}

}
